package javaNetTest;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * @author : yang.xp
 * @date : 2021/11/10 16:29
 * @description : 获得ip的工具类
 */
public class IpUtils {

    public static void main(String[] args) throws Exception {
        System.out.println(InetAddress.getLocalHost().getHostAddress());
        System.out.println(ipBytesToString(InetAddress.getLocalHost().getAddress()));
        printAddress();
    }

    public static String ipBytesToString(byte[] bytes) {
        if (bytes == null || bytes.length != 4) {
            return "127.0.0.1";
        }
        return (bytes[0] & 0xff) + "." + (bytes[1] & 0xff) + "." + (bytes[2] & 0xff) + "." + (bytes[3] & 0xff);
    }

    public static void printAddress() throws SocketException {
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface current = interfaces.nextElement();
            System.out.println(">> interface :" + current + " , index:" + current.getIndex() + ", virtual:" + current.isVirtual() + " loopback: " + current.isLoopback());
            Enumeration<InetAddress> address = current.getInetAddresses();
            while (address.hasMoreElements()) {
                InetAddress address1 = address.nextElement();
                System.out.println("  >> ip:" + address1);
            }
        }
    }

}
